<?php

namespace App\Jobs;

use App\Models\Personal;
use App\Models\StudyUserRecord;
use App\Models\StudyUserTime;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class StudyReaordTime implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $data;
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $data = $this->data;
        $time = $data['time'];
        try {
            //判断这个人这个课程有没有学习记录 如果有更新  如果没有 新增
            $user = Personal::where('id',$data['uid'])->first();
            if(!$user){
                Log::info($data['uid'].'用户不存在');
                return;
            }
            $is = StudyUserRecord::where('uid',$data['uid'])->where('course_id',$data['course_id'])->where('video_id',$data['video_id'])->first();
            if($is){
                $is->study_length = $data['study_length'];
                $is->update_time = $time;
                $is->save();
            }else{
                $insert = new StudyUserRecord();
                $insert->uid = $data['uid'];
                $insert->eid = $data['eid'];
                $insert->course_id = $data['course_id'];
                $insert->video_id = $data['video_id'];
                $insert->study_length = $data['study_length'];
                $insert->create_time = $time;
                $insert->update_time = $time;
                $insert->save();
            }
            Log::info($data['uid'].'RECORD记录完成');
            if($data['task_id'] > 0){
                return;
            }
            //根据时间节点记录时长
            $is_time = StudyUserTime::where('uid',$data['uid'])->where('course_id',$data['course_id'])->where('video_id',$data['video_id'])->first();
            //同一个视频时长为一条记录
            if($is_time){
                $is_time->increment('study_length',60);
            }else{
                $is_time = new StudyUserTime();
                $is_time->uid = $data['uid'];
                $is_time->eid = $data['eid'];
                $is_time->course_id = $data['course_id'];
                $is_time->video_id = $data['video_id'];
                $is_time->study_length = 60;
                $is_time->create_time = $time;
                $is_time->update_time = $time;
                $is_time->save();
            }

            
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw $th;
        }
    }
}
